package com.deplume.ssm.controller.admin;

import com.deplume.ssm.common.Json;
import com.deplume.ssm.common.Page;
import com.deplume.ssm.pojo.admin.*;
import com.deplume.ssm.pojo.extra.ChangeStatus;
import com.deplume.ssm.service.inface.admin.ICompanyRelativeService;
import com.deplume.ssm.service.inface.admin.IResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by libing on 2016/7/23.
 */
@Controller
@RequestMapping("/admin")
public class adminController {

    @Autowired
    ICompanyRelativeService companyRelativeService;

    @Autowired
    IResumeService resumeService;

    @RequestMapping("jumpToJsp")
    public String jumpToAdminJsp(HttpSession session, Model model)throws Exception{
        return "admin/admin";
    }


    @RequestMapping("admin/login")
    public String login(HttpSession session, Model model, @RequestParam String username,@RequestParam String p) throws Exception
    {
        if(username.equals("admin")&&p.equals("admin"))
        {
            session.setAttribute("username",username);
            model.addAttribute("username",username);
            return "redirect:/admin/listAllResumes.action";
        }
        return null;
    }
    @RequestMapping("logout")
    public String logout(HttpSession session) throws Exception
    {
        session.invalidate();
        return "common/exit";
    }
    @RequestMapping("listAllResumes")
    public String listAllResumes(Model model, HttpServletRequest request) throws Exception
    {
        return "common/templateJSP";
    }
    @RequestMapping("returnCompanyInfo")
    public String returnCompanyInfo(Model model, HttpServletRequest request) throws Exception
    {
        List<CompanyDetail> list = companyRelativeService.returnCompanyInfo();
        for(CompanyDetail c:list)
        {
            System.out.println(c.getCompany()+" "+c.getaAddress());
        }
        model.addAttribute("list",list);
        return "admin/listAllCompany";
    }
    @RequestMapping("returnCompanyInfos")
    public String returnCompanyInfos(Model model,HttpServletRequest request,String page)throws Exception
    {
        Page page1 = new Page();
        page1.setPageSize(8);
        page1.setCurrentPage(Integer.valueOf(page));
        List<CompanyDetail> list = companyRelativeService.returnCompanyInfos(page1);
        model.addAttribute("list",list);
        model.addAttribute("currentPage",page1.getCurrentPage());
        return "admin/listAllCompany";
    }

    @RequestMapping("returnCompanyUsersByText")
    public String returnCompanyUsersByText(Model model, HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "currentPage",defaultValue = "1",required = false)int page, String companyName) throws Exception
    {
        //String companyName = request.getParameter("name");
        System.out.println("companyName:"+companyName);
        Page page1 = new Page();
        page1.setPageSize(8);
        page1.setName(companyName);
        if(page == 0)
        {
            page1.setCurrentPage(1);
        }else
        {
            page1.setCurrentPage(page);
        }
        System.out.println("companyName:"+page1.getName()+" "+page1.getCurrentPage());
        List<Company> list = companyRelativeService.returnCompanyUsersByText(page1);
        model.addAttribute("list",list);
        model.addAttribute("companyName",page1.getName());
        model.addAttribute("currentPage",page1.getCurrentPage());
        return "admin/listAllCompanyUsersByText";
    }


    @RequestMapping("changeStatus")
    public String changeStatus(Model model,HttpServletRequest request,String page,int status,int id,int flag) throws Exception
    {
        int nowStatus = 0;
        if(status == 0)
            nowStatus = 1;
        ChangeStatus changeStatus = new ChangeStatus();
        changeStatus.setId(id);
        changeStatus.setStatus(nowStatus);

        System.out.println(changeStatus.getId()+"    "+changeStatus.getStatus());

        companyRelativeService.changeStatus(changeStatus);
        System.out.println("flag:"+flag);
        if(flag == 1) {
            return "redirect:/admin/selectCompanyDetail.action?companyId=" + id;
        }
        else
        {
            return "redirect:/admin/returnCompanyUsers.action?page=" + page;
        }
    }
    @RequestMapping("returnCompanyUsers")
    public String returnCompanyUsers(Model model,HttpServletRequest request,Integer page) throws Exception
    {
        System.out.println("======================page=====================");
        System.out.println(page);
        System.out.println("======================page=====================");
        Page page1 = new Page();
        page1.setPageSize(8);
        page1.setCurrentPage(page);
        List<Company> list = companyRelativeService.returnCompanyUsers(page1);
        model.addAttribute("list",list);
        model.addAttribute("currentPage",page1.getCurrentPage());
        return "admin/listAllCompanyUsers";
    }

    @RequestMapping("deleteCompanyUserById")
    public String deleteCompanyUserById(Model model,HttpServletRequest request,Integer id,int page) throws Exception
    {
        companyRelativeService.deleteCompanyUserById(id);
        return "redirect:/admin/returnCompanyUsers.action?page="+page;
    }

    //批量删除
    @RequestMapping("deleteCompanyUsers")
    public String deleteCompanyUsers(Integer[] items_id) throws Exception{
        //调用service方法，删除之前要先删除含有company_id为外键的表数据
        // 实现的方法是在d_company这个表里添加触发器
        //CREATE TRIGGER d_company_trigger BEFORE DELETE ON d_company
        //FOR EACH ROW
        //       BEGIN
        //DELETE FROM d_company_detail WHERE d_company_detail.company_id = old.company_id;
        //END
        // d_resume,d_company_detail
        System.out.println("---------deleteItems-----");
        for(Integer i : items_id) {
            System.out.println("---------items_id-------" +i);
        }
        companyRelativeService.deleteSelectedItems(items_id);
        return "redirect:/admin/returnCompanyUsers.action?page=1";
    }

    @RequestMapping("selectCompanyDetail")
    public String selectCompanyDetail(Model model, HttpServletRequest request,int companyId)throws Exception
    {
        System.out.println(companyId);
        CompanyDetail companyDetail = companyRelativeService.selectCompanyDetail(companyId);
        model.addAttribute("companyDetail",companyDetail);
        return "admin/listCompanyDetails";
    }



    @RequestMapping("editAllCompanyInfo")
    public String editAllCompanyInfo(Model model,HttpServletRequest request,Company company,int companyId) throws Exception
    {
        System.out.println("name:"+company.getCompanyName()+" "+companyId);
        company.setCityId(companyRelativeService.returnCityId(company.getCityName()));
        company.setCompanyId(companyId);
        if(company.getSex().equals("男"))
        {
            company.setContacterSex(0);
        }
        else
        {
            company.setContacterSex(1);
        }
        if(company.getStatus().equals("正常状态"))
        {
            company.setsStatus(0);
        }
        else
        {
            company.setsStatus(1);
        }
        System.out.println("==================");
        System.out.println(company.getCompanyId()+" "+company.getCompanyName()+""+company.getContacterName()+" "+company.getContacterSex()+" "+company.getCityId()+" "+company.getsStatus()+" "+company.geteEmail());
        System.out.println("==================");
        companyRelativeService.editAllCompanyInfo(company);
        return "redirect:/admin/selectCompanyDetail.action?companyId="+companyId;
    }


    @RequestMapping("editCompanyHeadImg")
    public String editCompanyDetails(Model model,HttpServletRequest request, MultipartFile companyImg, CompanyDetail companyDetail)throws Exception{
        System.out.println("companyDetailId:"+companyDetail.getCompanydetailId());
        System.out.println("companyId:"+companyDetail.getCompanyId());

        String originalFileName = companyImg.getOriginalFilename();
        if((companyImg != null) && (originalFileName != null) &&
                (originalFileName
                        .length() > 0)){
            String image_path = "F:\\image\\";
            String newFileName = UUID.randomUUID() + originalFileName
                    .substring(originalFileName.lastIndexOf("."));
            File newFile = new File(image_path + newFileName);
            companyImg.transferTo(newFile);
            companyDetail.setLogo(newFileName);
        }

        companyRelativeService.updateCompanyHeadImg(companyDetail);

        return "redirect:/admin/selectCompanyDetail.action?companyId="+companyDetail.getCompanyId();
    }


    @RequestMapping("editCompanyDetails")
    public String editCompanyDetails(Model model,HttpServletRequest request, CompanyDetail companyDetail, MultipartFile companyLicenceUrl)throws Exception{
        System.out.println("companyDetailId:"+companyDetail.getCompanydetailId());
        System.out.println("companyId:"+companyDetail.getCompanyId());
        String[] args = companyDetail.getSecIndustryName().split("/");
        List<String> list = new ArrayList<>();
        for (String name:args){
            System.out.println("name"+name);
            list.add(name);
        }
        System.out.println("mainindustryName================:"+companyDetail.getMainIndustryName());
        int mainIndustryId = companyRelativeService.selectMainIndustryId("%"+companyDetail.getMainIndustryName()+"%");
        System.out.println("id================:"+mainIndustryId);
        int companySizeId = companyRelativeService.selectCompanySizeId("%"+companyDetail.getCompanySizeName()+"%");
        System.out.println("id================:"+companySizeId);
        int companyPropertyId = companyRelativeService.selectCompanyPropertyId("%"+companyDetail.getCompamyPropertyName()+"%");
        System.out.println("id================:"+companyPropertyId);
        companyDetail.setMainindustryId(mainIndustryId);
        companyDetail.setCompanysizeId(companySizeId);
        companyDetail.setCompanypropertyId(companyPropertyId);

        companyRelativeService.deleteSecIndustry(companyDetail.getCompanydetailId());
        companyRelativeService.insertSecIndustry(companyDetail.getCompanydetailId(),list);

        String originalFileName = companyLicenceUrl.getOriginalFilename();
        if(companyLicenceUrl != null && originalFileName != null &&
                originalFileName.length() > 0){
            String url_path = "F:\\image\\";
            String newFileName = UUID.randomUUID() + originalFileName
                    .substring(originalFileName.lastIndexOf("."));
            File newFile = new File(url_path + newFileName);
            companyLicenceUrl.transferTo(newFile);
            companyDetail.setLicenceUrl(newFileName);
        }
        System.out.println(companyDetail.getCompanyId());
        companyRelativeService.updateCompanyDetailInfo(companyDetail);
        return "redirect:/admin/selectCompanyDetail.action?companyId="+companyDetail.getCompanyId();
    }




    @RequestMapping("returnResumesInfo")
    public String returnResumesInfo(Model model,HttpServletRequest request,int status)throws Exception
    {
        Page page = new Page();
        page.setPageSize(8);
        page.setCurrentPage(1);
        page.setStatus(status);
        List<Resume> list = resumeService.returnResumes(page);
        model.addAttribute("list",list);
        model.addAttribute("status",status);
        return "admin/listAllResumes";
    }


    @RequestMapping(value = "requestJson",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    public @ResponseBody List<Resume> requestJson(Model model,Json json)throws Exception{
        Page page = new Page();
        page.setPageSize(8);
        page.setCurrentPage(json.getPage());
        page.setStatus(json.getStatus());
        List<Resume> list = resumeService.returnResumes(page);
        return list;
    }

    @RequestMapping("selectResumeById")
    public String selectResumeById(Model model,HttpServletRequest request,int resumeId)throws Exception{
        System.out.println(resumeId);
        Resume resume = resumeService.selectResumeById(resumeId);
        System.out.println("======================================");
        System.out.println("liveCity:"+resume.getCity().getCityId());
        System.out.println("liveCity:"+resume.getCity().getCityName());
        System.out.println("schoolName:"+resume.getCustomer().getSchool().getSchoolName());
        System.out.println("======================================");
        Customer customer = resume.getCustomer();
        model.addAttribute("customer",customer);
        List<Education> educations = resume.getEducations();
        System.out.println("educationSize:"+educations.size());
        model.addAttribute("educations",educations);

        List<WorkExp> workExps = resume.getWorkExps();
        System.out.println("workExpSize:"+educations.size());
        model.addAttribute("workExps",workExps);

        List<Skill> skills = resume.getSkills();
        model.addAttribute("skills",skills);

        List<CompetitionExp> competitionExps = resume.getCompetitionExps();
        model.addAttribute("competitionExps",competitionExps);

        List<ExpectJobType> jobTypes = resumeService.expectJobTypeLists();
        System.out.println("jobTypesSize:"+jobTypes.size());
        model.addAttribute("jobTypes",jobTypes);


        List<SalaryType> salaryTypes = resumeService.expectSalaryLists();
        model.addAttribute("salaryTypes",salaryTypes);

        List<ExpectIndustry> expectIndustries = resumeService.expectIndustryLists();
        model.addAttribute("expectIndustries",expectIndustries);

        model.addAttribute("expectJobTypeId",resume.getExpectJobTypeId());
        model.addAttribute("expectIndustryId",resume.getExpectIndustryId());
        model.addAttribute("expectSalaryId",resume.getSalaryTypeId());

        return "admin/editResume";
    }
}
